#include "ApCfg.h"

#include <stdlib.h>
#include <string.h>
#include <stdio.h>

#include "common.h"

#include "list.h"

typedef struct _ApCfgNode ApCfgNode;
struct _ApCfgNode{
	char	index[100];
	char	value[100];
};
#define AP_CFG_STRIING_MAX	1024*10
struct _ApCfg{
	char strCfg[AP_CFG_STRIING_MAX];
	slist *listCfg;
};

ApCfg *ApCfg_new()
{
	ApCfg *pCfg = malloc(sizeof(ApCfg));
	if(pCfg){
		memset(pCfg, 0, sizeof(ApCfg));
	}
	return pCfg;
}

void ApCfg_free(ApCfg *pCfg)
{
	free(pCfg);
}

int ApCfg_init(ApCfg *pCfg)
{
	int nRet=0;
	char strCmd[1024];
	strcpy(strCmd, "cfg -e|awk '{print $2}'");
	nRet = get_cmd_result(strCmd, pCfg->strCfg, AP_CFG_STRIING_MAX);
	if(nRet){
		return nRet;
	}
	pCfg->listCfg = slist_new();
	char *pLine = strtok(pCfg->strCfg, "\r\n");
	while(pLine){
		printf("%s\n", pLine);
		char *pIndex=pLine;
		while(*pIndex){
			if(*pIndex=='='){
				*pIndex='\0';
				pIndex++;
				break;
			}
			pIndex++;
		}
		ApCfgNode *nodeCfg = malloc(sizeof(ApCfgNode));
		strcpy(nodeCfg->index, pLine);
		strcpy(nodeCfg->value, pIndex);
		//printf("Index=%s\tValue=%s\n", 
		//		nodeCfg->index, 
		//		nodeCfg->value);
		slist_push_back(pCfg->listCfg, nodeCfg);
		pLine = strtok(NULL, "\r\n");
	}
	return 0;
}

int ApCfg_get(ApCfg *pCfg, const char *pIndex, char *pValue, size_t slen)
{
	int nRet = 1;
	slist *list = pCfg->listCfg;
	node *pNode = ((node*)list)->next;
	while(pNode){
		ApCfgNode *pCfgNode = pNode->data;
		if(strcmp(pIndex, pCfgNode->index)==0){
			strncpy(pValue, pCfgNode->value, slen);
			nRet=0;
			break;
		}
		pNode = pNode->next;
	}
	return nRet;
}

int ApCfg_set(ApCfg *pCfg, const char *pIndex, const char *pValue)
{
	return 0;
}

void ApCfg_print(ApCfg *pCfg)
{
	printf("%s", pCfg->strCfg);
	slist *list = pCfg->listCfg;
	node *pNode = ((node*)list)->next;
	while(pNode){
		ApCfgNode *pCfgNode = pNode->data;
		printf("Index=%s\tValue=%s\n", 
				pCfgNode->index, 
				pCfgNode->value);
		pNode = pNode->next;
	}
}
